package com.xingzhe.pengji.security.services.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.xingzhe.pengji.security.dao.GroupIbatisDao;
import com.xingzhe.pengji.security.domain.Group;
import com.xingzhe.pengji.security.services.GroupService;

/**
 * @Title ： 三江学院 毕业设计
 * @Description ：
 * @author ：LuFengLiang
 * @Company: IT行者工作室
 * @Copyright: Copyright (c) 2012-2-24
 * @version ： 1.0
 * @param <T>
 */
@Service("groupService")
public class GroupServiceImpl<T extends Group> implements GroupService<T> {

	private static final Logger logger = LoggerFactory
			.getLogger(GroupServiceImpl.class);
	@Autowired
	private GroupIbatisDao<T> groupIbatisDao;

	@Override
	public List<T> queryForPageGroupList(T entity, String sortByColumn,
			int pageSize, int pageNumber, boolean sortAsc) {
		return groupIbatisDao.queryForPaginatedList(organizeParams(entity),
				pageNumber, pageSize, sortByColumn, sortAsc);
	}

	@Override
	public void saveGroup(T entity) {
		boolean b = groupIbatisDao.addGroup(entity);
		if (!b) {
			logger.error("新增用户组失败");
		}
	}

	@Override
	public void updateGroup(T entity) {
		boolean b = groupIbatisDao.updateGroup(entity);
		if (!b) {
			logger.error("更新用户组失败！");
		}
	}

	@Override
	public void delGroup(T entity) {
		entity.setDelFlag(-1);
		boolean b = groupIbatisDao.updateGroup(entity);
		if (!b) {
			logger.error("删除用户组失败！");
		}
	}

	@Override
	public T getGroupByName(T entity) {
		T group = groupIbatisDao.getGroupByName(entity);
		if (null != group) {
			return group;
		} else {
			return group;
		}
	}

	@Override
	public T getGroupById(T entity) {
		T group = groupIbatisDao.getGroupById(entity);
		if (null != group) {
			return group;
		} else {
			logger.error("该用户组不存在");
			return group;
		}
	}

	@Override
	public int getItemCount(T entity) {
		return groupIbatisDao.getItemCount(organizeParams(entity));
	}

	@SuppressWarnings("unchecked")
	private Map<String, Object> organizeParams(T entity) {
		if (null == entity) {
			entity = (T) new Group();
		}
		if (null != entity.getName() && ("".equals(entity.getName().trim()))) {
			entity.setName(null);
		}
		// 用于存放参数值的容器，用于Ibatis条件查询是取值
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("id", entity.getId());
		params.put("name", entity.getName());
		params.put("description", entity.getDescription());
		params.put("enabled", entity.getEnabled());

		return params;
	}

}
